const express = require("express");
const router = express.Router();

const Mate = require("../../models/UserMate");
const Init = require("../../models/UserInit");
const Score = require("../../models/Score");

const Upload = require("../../models/Upload");
const upload = require("../../config/upload");
const fs = require("fs");
const path = require("path");

const passport = require("passport");

router.get("/test", (req, res) => {
  res.json({ message: "Profile works" });
});

// @route  POST api/profiles/addmate
// @desc   添加自评材料接口
// @access Private
router.post(
  "/addmate",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const mateFields = {};

    if (req.body.number) mateFields.number = req.body.number;
    if (req.body.item) mateFields.item = req.body.item;
    if (req.body.grade) mateFields.grade = req.body.grade;
    if (req.body.prove) mateFields.prove = req.body.prove;
    if (req.body.module) mateFields.module = req.body.module;
    if (req.body.order) mateFields.order = req.body.order;

    new Mate(mateFields).save().then((profile) => {
      res.json(profile);
    });
  }
);

// @route  POST api/profiles/addinit
// @desc   将单个数据添加进自评模块表
// @access Private
router.post(
  "/addinit",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const moduleFields = {};

    if (req.body.number) moduleFields.number = req.body.number;
    if (req.body.moduleA) moduleFields.moduleA = req.body.moduleA;
    if (req.body.moduleB) moduleFields.moduleB = req.body.moduleB;
    if (req.body.moduleC) moduleFields.moduleC = req.body.moduleC;
    if (req.body.moduleD) moduleFields.moduleD = req.body.moduleD;
    if (req.body.moduleE) moduleFields.moduleE = req.body.moduleE;

    new Init(moduleFields).save().then((profile) => {
      res.json(profile);
    });
  }
);

// @route  POST api/profiles/addainitall
// @desc   将多个数据添加进自评模块表
// @access Private
router.post(
  "/addinitall",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    // 检查 req.body 是否为数组
    if (!Array.isArray(req.body)) {
      return res.status(400).json({ error: "tableData must be an array" });
    }

    // 获取 数组
    const tableData = req.body;
    // 使用 Promise.all 批量保存每个对象到数据库
    Promise.all(
      tableData.map((item) => {
        const moduleFields = { ...item }; // 拷贝对象，避免直接修改 req.body
        return new Init(moduleFields).save();
      })
    )
      .then((profiles) => {
        res.json({ message: "All records added successfully", profiles });
      })
      .catch((error) => {
        res.status(500).json({
          error: "Failed to add records",
          errorMessage: error.message,
        });
      });
  }
);

// @route  GET api/profiles/mate
// @desc   获取所有自评材料
// @access Private
router.get(
  "/mate",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Mate.find()
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }

        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route  GET api/profiles/getinit
// @desc   获取所有初始模块表
// @access Private
router.get(
  "/getinit",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Init.find()
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }

        res.json(profile);
      })
      .catch((err) => res.status(404).json("getinit失败"));
  }
);

// @route  GET api/profiles/getinit/:number
// @desc   根据学号获取初始模块表
// @access Private
router.get(
  "/getinit/:number",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Init.findOne({ number: req.params.number })
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }

        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route  POST api/profiles/scoreall
// @desc   将多个数据添加进学分表
// @access Private
router.post(
  "/scoreall",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    // 检查 req.body 是否为数组
    if (!Array.isArray(req.body)) {
      return res.status(400).json({ error: "tableData must be an array" });
    }

    // 获取 数组
    const tableData = req.body;

    //使用 Promise.all 批量保存每个对象到数据库
    Promise.all(
      tableData.map((item) => {
        const scoreFields = { ...item }; // 拷贝对象，避免直接修改 req.body
        return new Score(scoreFields).save();
      })
    )
      .then((profiles) => {
        res.json({ message: "score添加成功", profiles });
      })
      .catch((error) => {
        res.status(500).json({
          error: "score添加失败",
          errorMessage: error.message,
        });
      });
  }
);

// @route  delete api/profiles/deletescore
// @desc   将score数据表清除
// @access Private
router.delete(
  "/deletescore",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Score.deleteMany({})
      .then((profile) => {
        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route  GET api/profiles/getscore
// @desc   获取score数据表
// @access Private
router.get(
  "/getscore",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Score.find()
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }

        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route  GET api/profiles/mate/:number
// @desc   根据学号获得对应的自评材料表
// @access Private
router.get(
  "/mate/:number",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Mate.find({ number: req.params.number })
      .then((profile) => {
        if (!profile) {
          return res.status(404).json("没有任何内容");
        }

        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route  POST api/profiles/editmate/:id
// @desc   根据id编辑对应的自评事项
// @access Private
router.post(
  "/editmate/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const mateFields = {};

    if (req.body.number) mateFields.number = req.body.number;
    if (req.body.item) mateFields.item = req.body.item;
    if (req.body.grade) mateFields.grade = req.body.grade;
    if (req.body.prove) mateFields.prove = req.body.prove;
    if (req.body.module) mateFields.module = req.body.module;
    if (req.body.order) mateFields.order = req.body.order;

    Mate.findOneAndUpdate(
      { _id: req.params.id },
      { $set: mateFields },
      { new: true }
    ).then((mate) => res.json(mate));
  }
);

// @route  delete api/profiles/deletemate/:id
// @desc   根据id删除事项
// @access Private
router.delete(
  "/deletemate/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Mate.findByIdAndDelete(req.params.id)
      .then((profile) => {
        if (!profile) {
          return res.status(404).json({ nop: "id不存在" });
        }
        res.json({ success: true });
      })
      .catch((err) => {
        console.error(err);
        res.status(404).json({ nop: "删除错误" });
      });
  }
);

//使用findOneAndRemove方法删除数据失败
// router.delete(
//   "/deletemate/:id",
//   passport.authenticate("jwt", { session: false }),
//   (req, res) => {
//     Mate.findOneAndRemove({ _id: mongoose.Types.ObjectId(req.params.id) })
//       .then((profile) => {
//         if (!profile) {
//           return res.status(404).json({ nop: "id不存在" });
//         }
//         res.json({ success: true });
//         //profile.save().then((profile) => res.json(profile));
//       })
//       .catch((err) => res.status(404).json("删除失败!"));
//   }
// );

// @route  POST api/profiles/addinitall
// @desc   将多个数据添加进自评模块表
// @access Private
router.post(
  "/addinitall",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    // 检查 req.body 是否为数组
    if (!Array.isArray(req.body)) {
      return res.status(400).json({ error: "tableData must be an array" });
    }

    // 获取 数组
    const tableData = req.body;
    //将Init数据表清除
    // Init.deleteMany({});

    //使用 Promise.all 批量保存每个对象到数据库
    Promise.all(
      tableData.map((item) => {
        const moduleFields = { ...item }; // 拷贝对象，避免直接修改 req.body
        return new Init(moduleFields).save();
      })
    )
      .then((profiles) => {
        res.json({ message: "All records added successfully", profiles });
      })
      .catch((error) => {
        res.status(500).json({
          error: "Failed to add records",
          errorMessage: error.message,
        });
      });
  }
);

// @route  delete api/profiles/deleteinitall
// @desc   将Init数据表清除
// @access Private
router.delete(
  "/deleteinitall",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Init.deleteMany({})
      .then((profile) => {
        res.json(profile);
      })
      .catch((err) => res.status(404).json(err));
  }
);

// @route  POST api/profiles/upload
// @desc   上传图片
// @access Private
router.post(
  "/upload",
  passport.authenticate("jwt", { session: false }),
  upload.single("file"),
  (req, res) => {
    const file = req.file;
    //打印上传的文件信息
    //console.log("file:", file);
    const filePath = `public/uploads/${file.filename}`;
    fs.rename(file.path, filePath, (err) => {
      if (err) {
        console.error(err);
        return res.status(501).send(err);
      }
      // 存储文件路径到数据库Upload表中
      // const uploadFile = filePath;
      //console.log("uploadFile赋值成功");
      const uploadData = {
        path: filePath,
      };
      new Upload(uploadData).save().then((data) => {
        //console.log("上传到数据库成功:" + uploadData.path);
      });
      // 完成图片上传
      res.send({
        url: `http://localhost:5000/${filePath}`,
        path: filePath,
        filename: file.filename,
      });
    });
  }
);

// @route  delete api/profiles/deleteUpload/:fileName
// @desc   删除上传图片
// @access Private
router.delete(
  "/deleteUpload/:fileName",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    const fileName = req.params.fileName;
    const path = `public/uploads/${fileName}`;
    //查找文件记录
    //console.log("path:", path);
    const fileRecord = await Upload.findOne({ path: path });
    if (!fileRecord) {
      return res.status(409).json({ error: "File not found" });
    }
    //删除文件
    //const filePath = `public/uploads/${fileName}`;
    fs.unlink(path, (err) => {
      if (err) {
        console.error(err);
        return res.status(500).send(err);
      }
      // 删除数据库记录
      Upload.deleteOne({ path: path }).then(() => {
        res.json({ message: "File deleted successfully" });
      });
    });
  }
);

// @route  get api/profiles/getUpload/:fileName
// @desc   获得上传图片
// @access Private
router.get(
  "/getUpload/:fileName",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const fileName = req.params.fileName;
    //使用path模块获取文件路径绝对路径pathAll，以便于使用sendFile方法发送文件
    pathAll = path.join(__dirname, "../../", "public", "uploads", fileName);
    //console.log("pathAll终端打印:", pathAll);
    res.sendFile(pathAll, (err) => {
      if (err) {
        console.error(err);
        return res.status(500).send(err);
      }
    });
  }
);

module.exports = router;
